
#include "datastructure.hpp"
#include "myLog4.h"
#include "interationfastapi.hpp"
#include <cstring>

ThreadSafeQueue<std::string> uavExecuteCommandsQueue;
const int socketReceiverBufferSize = ConfigManager::GetSocketReceiverBufferSize();

void receivePythonData(int serverSocketfd, sockaddr_in serverAddr, ThreadSafeQueue<std::string>& uavExecuteCommandsQueue) {
    /**
    * @brief socket服务端,被连接后若接收到发送来的数据,将其push进shareQueue中
    * @param serverSocketfd  本身socket初始化信息
    * @param serverAddr   本身IP(本身即服务端)
    * @param uavExecuteCommandsQueue  共享队列，与函数consumerFun共享，存放获取的数据（字符串），也可后期处理后再存放进去
    */
    bool isBind = false;
    // 设置 SO_REUSEADDR 选项
    int flag = 1;
    if (setsockopt(serverSocketfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == -1) {
        LOG_ERROR("[log4]" << "设置 SO_REUSEADDR 失败");
        return;
    }
    while (true){
        if(!isBind){
            for (int attempt = 1; attempt <= 5; ++attempt) {
                LOG_INFO("[log4]" << LOG4CPLUS_TEXT("尝试绑定开放的端口给fastapi,尝试次数:") << attempt);
                if (bind(serverSocketfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == 0) {
                    LOG_INFO("[log4]" << "绑定成功,尝试监听");
                    isBind = true;
                    break;
                    }
                    std::this_thread::sleep_for(std::chrono::seconds(5));
                }
        }

        if (!isBind) LOG_ERROR("[log4]" << "失败太多次，请检查其他原因..."); 
        // 监听连接
        if (listen(serverSocketfd, 5) == -1) {
            LOG_ERROR("[log4]" << "监听fastapi失败"); 
            return ;
        }
        // 等待连接
        std::string message = "开放端口:";
        message +=  std::to_string(RECEIVEFROMPYTHONPORT);
        message += "等待客户端(fastapi)连接...";
        LOG_INFO("[log4]" << message);

        sockaddr_in clientAddr;
        socklen_t clientAddrLen = sizeof(clientAddr);
        int clientSocket = accept(serverSocketfd, (struct sockaddr*)&clientAddr, &clientAddrLen);
        if (clientSocket == -1) {
            LOG_ERROR("[log4]" << "接受fastapi连接失败"); 
            return;
        }
        LOG_INFO("[log4]" << "fastapi连接成功");

        char buffer[socketReceiverBufferSize];
        while (true) {
            memset(buffer, 0, sizeof(buffer));
            int bytesReceived = recv(clientSocket, buffer, sizeof(buffer), 0);
            if (bytesReceived == -1) {
                LOG_ERROR("[log4]" << "接收到fastapi请求但连接错误");
                break;
            }
            if (bytesReceived == 0) {
                LOG_ERROR("[log4]" << "fastapi断开连接");
                break;
            }
            LOG_INFO("[log4]" << LOG4CPLUS_TEXT("收到fastapi数据: ") << buffer);
            uavExecuteCommandsQueue.push(buffer);
        }
        close(clientSocket);
   }
}